import {isTextFieldEntryEdited, SelectEntry} from "@bpmn-io/properties-panel";
import {useService} from "bpmn-js-properties-panel";
import {is} from "bpmn-js/lib/util/ModelUtil";
import {jsx} from "@bpmn-io/properties-panel/preact/jsx-runtime";

const component = {
  id: 'eventType',
  component: EventType,
  isEdited: isTextFieldEntryEdited
}

if(window['register']) {
  window['register'].regComponent(component.id,component)
}
export default function(element) {
  component['element']=element;
  return component;
}

function EventType(props) {
  const { element, id,listener } = props;
  const translate = useService('translate');
  const bpmnFactory = useService('bpmnFactory');
  const commandStack = useService('commandStack');
  function getValue() {
    return listener.get('event');
  }
  function setValue(value) {
    const properties = getDefaultEventTypeProperties(value, bpmnFactory);
    commandStack.execute('element.updateModdleProperties', {
      element,
      moddleElement: listener,
      properties
    });
  }
  function getOptions() {
    if (is(listener, 'activiti:TaskListener')) {
      return [{
        value: 'all',
        label: translate('all')
      },{
        value: 'create',
        label: translate('create')
      }, {
        value: 'assignment',
        label: translate('assignment')
      }, {
        value: 'complete',
        label: translate('complete')
      }, {
        value: 'delete',
        label: translate('delete')
      }];
    }
    if (is(element, 'bpmn:SequenceFlow')) {
      return [{
        value: 'take',
        label: translate('take')
      }];
    }
    return [{
      value: 'start',
      label: translate('start')
    }, {
      value: 'end',
      label: translate('end')
    },{
      value: 'take',
      label: translate('take')
    }];
  }
  return jsx(SelectEntry, {
    id: id,
    label: translate('Event type'),
    getValue: getValue,
    setValue: setValue,
    getOptions: getOptions
  });
}
const DEFAULT_EVENT_PROPS = {
  'eventDefinitions': undefined,
  'event': undefined
};
function getDefaultEventTypeProperties(type, bpmnFactory) {
  switch (type) {
    case 'timeout':
      return {
        ...DEFAULT_EVENT_PROPS,
        eventDefinitions: [bpmnFactory.create('bpmn:TimerEventDefinition')],
        event: type
      };
    default:
      return {
        ...DEFAULT_EVENT_PROPS,
        event: type
      };
  }
}
